﻿namespace EasyGo.Services.Impl
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Web.Caching;

    using EasyGo.Data;
    using EasyGo.Data.Dao;
    using EasyGo.Domain.Model;
    using System.Web;

    public class CompanyService : Service, ICompanyService
    {
        private readonly ICompanyDao companyDao;

        private readonly EasyGoDbContext db;

        private const string CompanyDictionaryCacheKey = "CompanyDictionary";

        public CompanyService(ICompanyDao companyDao, EasyGoDbContext dbContext)
        {
            this.companyDao = companyDao;
            this.db = dbContext;
        }

        public Company CreateCompany(Company company)
        {
            company.Id = companyDao.CreateCompany(company);
            this.SaveChanges();
            this.RemoveCacheItem(CompanyDictionaryCacheKey);
            return company;
        }

         public Company GetById(int id)
         {
             return companyDao.GetById(id);
         }

        public IEnumerable<Company> GetAllCompanies()
        {
            return companyDao.GetAllCompanies();
        }

        public void UpdateCompany(Company company)
        {
            companyDao.UpdateCompany(company);
            this.SaveChanges();
            this.RemoveCacheItem(CompanyDictionaryCacheKey);
        }

        public void Delete(int id)
        {
            companyDao.Delete(id);
            this.SaveChanges();
            this.RemoveCacheItem(CompanyDictionaryCacheKey);
        }

        public IEnumerable<DictionaryItem> GetCompantDictionary()
        {
            var item = HttpContext.Current.Cache.Get(CompanyDictionaryCacheKey);
            if (item == null)
            {
                var result = db.Companies.Select(x => new DictionaryItem() { Id = x.Id, Name = x.Name }).ToList();
                this.SetCacheItem(CompanyDictionaryCacheKey, result);
                return result;
            }
            return item as IEnumerable<DictionaryItem>;
        }
    }
}
